package servlet;

import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;


@WebServlet("/updateUser")
@MultipartConfig
public class UserPrepareUpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 2L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		String realName = request.getParameter("realName");
		String nickname = request.getParameter("nickname");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String role = request.getParameter("role");
		String headImg = request.getParameter("aheadImg");
		Collection<Part> collection = request.getParts();
		Iterator<Part> iter = collection.iterator();
		StringBuilder sb = new StringBuilder();
		while(iter.hasNext()) {
			Part part = iter.next();
			String partName = part.getName();
			System.out.println(partName + "," + part.getSize() + "," + part.getContentType());
			String fileName = getFileName(part);
			if (fileName == null) continue;
			System.out.println("文件名：" + fileName);
			part.write("d:/tmp/img/" + fileName);
			if (sb.length() != 0) sb.append(", ");
			sb.append( "http://localhost:8080" + request.getContextPath() + "/download.do?f=" + fileName);
		}
		if (!sb.toString().isEmpty()){
			headImg = sb.toString();
		}
		UserDao userDao = new UserDao();
		int ret = userDao.updateUser(password,realName,email,nickname,headImg,phone,role,account);
		if(ret == -1) {
			response.sendRedirect("error.jsp");
			return;
		}else {
			request.getSession().setAttribute("successMsg", "修改成功！");
			request.getRequestDispatcher("userList").forward(request, response);
		}
	}

	public String getFileName(Part part) {
		if (part.getSize() == 0 || part.getContentType() == null) return null;
		String header = part.getHeader("Content-Disposition");//获得Content-Disposition的头信息
		int idx = header.lastIndexOf("filename=\"");//获取filename=“字符串的开始下标
		String fileName = header.substring(idx+"filename=\"".length(), header.length()-1);
		return fileName;
	}
}
